package aframe.http.net;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import aframe.http.Http;
import aframe.http.bean.HttpTask;
import aframe.http.callback.HttpCallBack;
import aframe.utils.LogUtils;



public class AsyncHttp {
	public static final int RESPONSE_CODE_OK = 200;

	private static AsyncHttp instance = new AsyncHttp();
	private ThreadPoolExecutor executor;

	private AsyncHttp() {
		executor = new ThreadPoolExecutor(5, 8, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10), new ThreadPoolExecutor.DiscardOldestPolicy());
	}

	public static AsyncHttp getInstance() {
		return instance;
	}

	public void doTask(final HttpTask task, final HttpCallBack callBack) {
		doTask(task, callBack, Http.CHARSET_UTF_8);
	}

	public void doTask(final HttpTask task, final HttpCallBack callBack, final String charset) {
		executor.execute(new Runnable() {
			public void run() {
				HttpTask newTask = null;
				try {
					newTask = new DealHttp(charset).request(task);
				} catch (Exception e) {
					LogUtils.exception(e);
					newTask = task;
				}
				if (callBack != null) {
					callBack.callBack(newTask);
				}
			}
		});
	}

}
